package com.ytph.zxing;

import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * zxing 二维码
 * @author administrator
 *
 */
public class CreateQrCode {
	public static void main(String[] args) {
		int width = 300;
		int height = 300;
		//格式
		String format = "png";
		//内容
		String content = "http://www.baidu.com";
		
		//定义二维码的参数
		HashMap hints = new HashMap<>();
		//字符集
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		//纠错等级  H  L  M  Q  一般用m
		hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);
		//边距
		hints.put(EncodeHintType.MARGIN, 2);
		
		// 第二个参数是指定二维码的编码
		try { 
			 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
			 //生成二维码
			 Path file = new File("D:/code/img.png").toPath();
			 MatrixToImageWriter.writeToPath(bitMatrix, format, file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
